﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Color = System.Drawing.Color;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;

namespace classTest
{
    /// <summary>
    /// ClassBreaksRenderWindow.xaml 的交互逻辑
    /// </summary>
    /// 
    public partial class ClassBreaksRenderWindow : Window
    {
        private string sFieldName;
        private Color cclassColor = Color.Blue;
        private int cclassCount =5;
        private ClassBreaksRenderer pCBRenderer;

        private FeatureLayer layer;
        private Renderer pSymbol;

        public MainWindow mainWindow { get; set; }

        public ClassBreaksRenderWindow(MainWindow mainWindow1)
        {
            InitializeComponent();
            mainWindow = mainWindow1;

            Initialize();
        }

        private void Initialize()
        {
            List<string> layerName = new List<string>();
            LayerCollection pLayers = mainWindow.MyMapView.Map.OperationalLayers;
            //for循环地图业务图层的所有图层名称与参数进行比对，一旦匹配到相等即返回对应图层
            for (int i = pLayers.Count - 1; i >= 0; i--)
            {
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = pLayers[i].Name;
                cbi.DataContext = pLayers[i];
                layerComboBox.Items.Add(cbi);
            }
            layerComboBox.SelectedIndex = 0;
        }

        //显示可选字段
        private void viewBasePage()
        {
            ClassBreaksListBox.Items.Clear();
            layer = (layerComboBox.SelectedItem as ComboBoxItem).DataContext as FeatureLayer;
            List<string> names = new List<string>();
            for (int i = 0; i < layer.FeatureTable.Fields.Count; i++)
            {
                FieldType type = layer.FeatureTable.Fields[i].FieldType;
                if(type!= FieldType.Text)
                {
                    ListBoxItem lb = new ListBoxItem();
                    lb.Content = layer.FeatureTable.Fields[i];
                    lb.Height = 25;
                    lb.FontSize = 13;
                    if(!ClassBreaksListBox.Items.Contains(lb))
                    ClassBreaksListBox.Items.Add(lb);
                }
            }
            if (ClassBreaksListBox.Items.Count > 0)
            {
                ClassBreaksListBox.SelectedIndex = 0;
                SetClassBreaksRender(layer, sFieldName);
            }

            pSymbol = layer.Renderer;
           
        }

        // 选择字段
        private void ClassBreaksListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ClassBreaksListBox.SelectedIndex == -1) return;
            ListBoxItem lp = ClassBreaksListBox.Items[ClassBreaksListBox.SelectedIndex] as ListBoxItem;
            sFieldName = lp.Content.ToString();
            SetClassBreaksRender(layer, sFieldName, cclassCount);
        }

        // 选择颜色
        private void ClassBreaksColorRectangle_MouseDown(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Forms.ColorDialog clrDlg = new System.Windows.Forms.ColorDialog();
            if (clrDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                cclassColor = clrDlg.Color;
                System.Windows.Media.Color c = System.Windows.Media.Color.FromArgb(cclassColor.A, cclassColor.R, cclassColor.G, cclassColor.B);
                ClassBreaksColorRectangle.Fill = new SolidColorBrush(c);
                SetClassBreaksRender(layer, sFieldName, cclassCount);
            }
        }

        //选图层
        private void LayerComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            viewBasePage();
        }

        // 选择分级次数
        private void ClassBreaksTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                cclassCount = Convert.ToInt32(ClassBreaksTextBox.Text);
            }
            catch
            {
                cclassCount = 5;
            }
        }

        // 确定
        private void ClassBreaksOKBtn_Click(object sender, RoutedEventArgs e)
        {
            if(pCBRenderer!=null)
            layer.Renderer = pCBRenderer;
            Close();
        }

        // 应用
        private void ClassBreaksApplyBtn_Click(object sender, RoutedEventArgs e)
        {
            if (pCBRenderer != null)
            {
                layer.Renderer = pCBRenderer.Clone();
            }

        }

        // 取消
        private void ClassBreaksCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            layer.Renderer = pSymbol;
            Close();
        }

        // 设置渲染器
        private async void SetClassBreaksRender(FeatureLayer pLayer, string saFieldName, int ClassifyCount = 5)
        {
            try
            {
                pLayer = layer;
                saFieldName = sFieldName;
                ClassNumberListBox.Items.Clear();
                //Console.WriteLine("pLayer: " + pLayer + "  sFieldName:" + saFieldName + "  ClassifyCount:" + ClassifyCount);
                pCBRenderer = new ClassBreaksRenderer();
                ////设置字段名
                pCBRenderer.FieldName = sFieldName;
                //设置统计查询条件，
                StatisticDefinition statDefinitionMin = new StatisticDefinition(saFieldName, StatisticType.Minimum, "");
                StatisticDefinition statDefinitionMax = new StatisticDefinition(saFieldName, StatisticType.Maximum, "");
                List<StatisticDefinition> statDefinitions = new List<StatisticDefinition> { statDefinitionMin, statDefinitionMax, };
                StatisticsQueryParameters pQueryPara = new StatisticsQueryParameters(statDefinitions);
                //执行统计查询
                StatisticsQueryResult queryResult = await pLayer.FeatureTable.QueryStatisticsAsync(pQueryPara);
                //从统计结果中获取最大值，获取最小值
                string str;
                object max = null, min = null;
                double dMax, dMin;
                //获取该字段的最大值，最小值，为后续分级做准备
                IReadOnlyDictionary<string, object> sResult = queryResult.First().Statistics;
                for (int i = 0; i < sResult.Count; i++)
                {
                    str = sResult.Keys.ElementAt(i);
                    if (str.Contains("MAX"))
                        max = sResult.Values.ElementAt(i);
                    if (str.Contains("MIN"))
                        min = sResult.Values.ElementAt(i);
                }
                try
                {
                    dMax = Convert.ToDouble(max);
                    dMin = Convert.ToDouble(min);
                }
                catch
                {
                    MessageBoxResult ac = MessageBox.Show("此字段类型不是数值！", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                //计算并设置分级中每一级别的范围，以及符号
                for (int i = 0; i < ClassifyCount; i++)
                {
                    ClassBreak pClassBreak = new ClassBreak();
                    //每一级别范围的最大值、最小值
                    double maxs, mins;
                    if (i == 0)
                        mins = dMin;
                    else
                        mins = dMin + (dMax - dMin) * i / ClassifyCount;
                    maxs = dMin + (dMax - dMin) * (i + 1) / ClassifyCount;
                    pClassBreak.MinValue = mins;
                    pClassBreak.MaxValue = maxs + 0.1;

                    Color tempColor;
                    if (cclassColor.G < 50)
                    {
                        int cl = (235 - cclassColor.G) / ClassifyCount;
                        tempColor = Color.FromArgb(cclassColor.R, 235 - cl * i, cclassColor.B);
                    }
                    else
                    {
                        int cl = cclassColor.G / ClassifyCount;
                        tempColor = Color.FromArgb(cclassColor.R, cclassColor.G - cl * i, cclassColor.B);
                    }

                    GeometryType pLayerType = pLayer.FeatureTable.GeometryType;

                    ListBoxItem ln = new ListBoxItem();
                    ln.Content = Math.Round(mins, 2) + " - " + Math.Round(maxs, 2);
                    ln.Height = 20;
                    ln.FontSize = 12;
                    ln.DataContext = pLayerType;
                    ln.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(tempColor.R, tempColor.G, tempColor.B));
                    ln.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255));
                    ClassNumberListBox.Items.Add(ln);

                    Symbol cSymbol;
                    //创建符号，这里图层为面层，直接创建面符号，注意若图层为 点层、线层，需创建对应的点符号、线符号
                    if (pLayerType == GeometryType.Envelope || pLayerType == GeometryType.Polygon)
                    {
                        SimpleLineSymbol tempSymbol2 = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Gray, 1);
                        cSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, tempColor, tempSymbol2);
                    }else if(pLayerType == GeometryType.Polyline)
                    {
                        cSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, tempColor, 1);
                    }else if(pLayerType == GeometryType.Point || pLayerType == GeometryType.Multipoint)
                    {
                        cSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, tempColor, 5);
                    }
                    else
                    {
                        SimpleLineSymbol tempSymbol2 = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Gray, 1);
                        cSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, tempColor, tempSymbol2);
                    }
                    pClassBreak.Symbol = cSymbol;
                    //将设置好的ClassBreak放入ClassBreaksRenderer中。
                    pCBRenderer.ClassBreaks.Add(pClassBreak);
                }
            }
            catch (Exception e)
            {
                MessageBoxResult ac = MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ClassNumberListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = ClassNumberListBox.SelectedIndex;
            if (index == -1) return;
            ListBoxItem cbi = ClassNumberListBox.SelectedItem as ListBoxItem;
            System.Windows.Forms.ColorDialog clrDlg = new System.Windows.Forms.ColorDialog();
            if (clrDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Symbol cSymbol;
                cbi.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(clrDlg.Color.R, clrDlg.Color.G, clrDlg.Color.B));
                GeometryType pLayerType = (GeometryType)(cbi.DataContext);
                //创建符号，这里图层为面层，直接创建面符号，注意若图层为 点层、线层，需创建对应的点符号、线符号
                if (pLayerType == GeometryType.Envelope || pLayerType == GeometryType.Polygon)
                {
                    SimpleLineSymbol tempSymbol2 = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Gray, 1);
                    cSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, clrDlg.Color, tempSymbol2);
                }
                else if (pLayerType == GeometryType.Polyline)
                {
                    cSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, clrDlg.Color, 1);
                }
                else if (pLayerType == GeometryType.Point || pLayerType == GeometryType.Multipoint)
                {
                    cSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, clrDlg.Color, 5);
                }
                else
                {
                    SimpleLineSymbol tempSymbol2 = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Gray, 1);
                    cSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, clrDlg.Color, tempSymbol2);
                }
                pCBRenderer.ClassBreaks.ElementAt(index).Symbol = cSymbol;
                ClassNumberListBox.SelectedIndex = -1;
            }
        }
    }
}
